package com.higgins.eventtracking.client.health.fundamentals;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.higgins.eventtracking.client.EventTrackingService;
import com.higgins.eventtracking.client.EventTrackingServiceAsync;
import com.higgins.eventtracking.client.FinanceTrackingService;
import com.higgins.eventtracking.client.FinanceTrackingServiceAsync;
import com.higgins.eventtracking.client.SecurityAccessDeniedException;
import com.higgins.eventtracking.client.dto.DynamicTypeDTO;
import com.higgins.eventtracking.client.health.components.BodyStatsLoader;
import com.higgins.eventtracking.client.health.components.LastBodyStatsLoader;
import com.higgins.eventtracking.client.health.components.StatsLoader;
import com.higgins.eventtracking.client.health.record.entry.Exercise;

public class BodySubTab extends VerticalPanel	implements SubTab		{
	private final FinanceTrackingServiceAsync financeTrackingService = GWT
													.create(FinanceTrackingService.class);
	private final EventTrackingServiceAsync greetingService = GWT
													.create(EventTrackingService.class);

	private String bodyDynamicType = "ExerciseType";
	private String dynamicType = null;
	private String frameOfMind = null;
	private List<DynamicTypeDTO> dtos = null;
	private int maxRow = 20;
	private int maxColumn = 4;
	private Integer width = 175;
	private Integer height = 20;
	private List<List<Label>> labelRows = null;
	private List<StatsLoader> statsLoaders = null;
	
	public BodySubTab(String dynamicType, String frameOfMind, List<DynamicTypeDTO> dtos)	{
		this.dynamicType = dynamicType;
		this.frameOfMind = frameOfMind;
		this.dtos = dtos;
	}
	
	public void createTableStructure()	{
		List<Label> labelRow = new ArrayList<Label>();
		for (int rowIndex = 0; rowIndex <= maxRow; rowIndex++)	{
			HorizontalPanel rowPanel = new HorizontalPanel();
			rowPanel.setSpacing(0);
			for (int columnIndex = 0;columnIndex <= maxColumn; columnIndex++)	{
				Label label = new Label();
				label.setWidth(width+"px");
				label.setHeight(height + "px");
				labelRow.add(label);
				
				rowPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP);
				rowPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
				rowPanel.setHeight(height+"px");
				rowPanel.add(label);
				rowPanel.setCellHeight(label, "0px");
			}
			add(rowPanel);
			labelRows.add(labelRow);
			labelRow = new ArrayList<Label>();
		}		
	}

	@Override
	public void update() {
		resetView();
		addExerciseDataEntry();
		createTableStructure();
		populateFields();
	}
	
	private void resetView()	{
		clear();
		labelRows = new ArrayList<List<Label>>();
		statsLoaders = new ArrayList<StatsLoader>();
		setHeight("200px");
		setWidth("800px");
		setSpacing(0);
		setVerticalAlignment(HasVerticalAlignment.ALIGN_TOP);
		setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
	}
	
	private void addExerciseDataEntry()	{
		Exercise exerciseDataEntry = new Exercise();
		exerciseDataEntry.update();
		add(exerciseDataEntry);
	}
	
	private void populateFields()	{
		try	{
			financeTrackingService.retrieveDynamicTypes(bodyDynamicType, new AsyncCallback<List<DynamicTypeDTO>>()  {
	
				@Override
				public void onFailure(Throwable caught) {
	
				}
	
				@Override
				public void onSuccess(List<DynamicTypeDTO> result) {
				    Collections.sort(result, new Comparator<DynamicTypeDTO>() {
                        @Override
                        public int compare(DynamicTypeDTO arg0, DynamicTypeDTO arg1) {
                            if (arg0.getTimestamp()!=null && arg1.getTimestamp()!=null) {
                                return arg0.getTimestamp().compareTo(arg1.getTimestamp());
                            }
                            return 0;
                        }
				    
				    });
					String lastDynamicType = "";
					int rowIndex = 1;
					// Parent Items
					for (DynamicTypeDTO dtoLevel1:result)	{
						if (dtoLevel1.getSubType()==null || dtoLevel1.getSubType().equals(false))	{
							for (DynamicTypeDTO dtoLevel2:result)		{
								if (dtoLevel2.getSubType()!=null && dtoLevel2.getSubType().equals(true) && dtoLevel2.getDynamicType().equals(dtoLevel1.getDynamicType()))	{
									if (!lastDynamicType.equals(dtoLevel2.getDynamicType()))
										populateField(0, rowIndex, dtoLevel2.getDynamicType());
									populateField(1, rowIndex, dtoLevel2.getSubCategory());
									asyncPopulateMaxThisWeekField(2, rowIndex, dtoLevel2.getSubCategory());
									asyncPopulateMaxThisMonthField(3, rowIndex, dtoLevel2.getSubCategory());
									rowIndex++;
									lastDynamicType = dtoLevel2.getDynamicType();
								}
							}
						}
					}
				} });
		} catch (IllegalArgumentException e) {
	
		} catch (SecurityAccessDeniedException e) {
	
		}			
	}
	public void populateField(int columnIndex, int rowIndex, String text)	{
		if (columnIndex < maxColumn && rowIndex < maxRow)	{
			List<Label> labelRow = labelRows.get(rowIndex);
			Label label = labelRow.get(columnIndex);
			label.setText(text);
		}
	}
	public void asyncPopulateMaxThisWeekField(int columnIndex, int rowIndex, String text)	{
		if (columnIndex < maxColumn && rowIndex < maxRow)	{
			BodyStatsLoader statsLoader = new BodyStatsLoader(greetingService, this, columnIndex, rowIndex, text);
			statsLoader.execute();
			statsLoaders.add(statsLoader);
		}
	}
	
	public void asyncPopulateMaxThisMonthField(int columnIndex, int rowIndex, String text)	{
		if (columnIndex < maxColumn && rowIndex < maxRow)	{
			LastBodyStatsLoader statsLoader = new LastBodyStatsLoader(greetingService, this, columnIndex, rowIndex, text);
			statsLoader.execute();
			statsLoaders.add(statsLoader);
		}
	}
	
}
